<template>
  <div>
    <h1> {{id? '编辑': '新建'}}管理员</h1>
    <el-form label-width='100px' @submit.native.prevent='save'>
      <el-form-item label='用户名'>
        <el-input v-model="model.username"></el-input>
      </el-form-item>
      <el-form-item label='密码'>
        <el-input v-model="model.password"></el-input>
      </el-form-item>
      <el-form-item>
        <!-- native-type: 表示其原生类型是submit -->
        <el-button type='primary' native-type='submit'>保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  props: {
    id: {},
  },
  data() {
    return {
      model: {},
    };
  },
  methods: {
    async save() {
      let res
      if(this.id){
        // id存在则证明此时是编辑保存操作 => 更新数据
        res = await this.$http.put(`rest/admins/${this.id}`, this.model)
      }else {
        // 否则是新建保存操作 => 新增
        res = await this.$http.post("rest/admins", this.model);
      }
      if (res.data) {
        this.$message({
          type: "success",
          message: "保存成功",
        });
        this.$router.push("/admins/list");
      }
    },
    // 根据id查询分类信息
    async fetchById() {
      const res = await this.$http.get(`rest/admins/${this.id}`);
      this.model = res.data;
    },
  },
  created() {
    if (this.id) {
      this.fetchById();
    }
  },
};
</script>